package com.ruoyi.utils;

import com.ruoyi.po.Account;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 描述：便捷的Redis账户工具
 */
@Component
@Slf4j
public class EasyRedisAccountBeanUtil {

    /**
     * Redis操作的客户端
     */
    private StringRedisTemplate redisTemplate;

    /**
     * 系统配置项服务
     */
    private ISysConfigService configService;

    /**
     * 描述：获得Token
     * @author Cymal
     * @date 2024-06-29
     */
    public String getToken(Account account, String point) {
        Long id = account.getId();
        // 是否sso单点登录
        String sso = configService.selectConfigByKey("account.sso");
        if (Objects.equals(sso, "true")) {
            return redisTemplate.opsForValue().get("account:token:" + point + ":" + id);
        }
        return redisTemplate.opsForValue().get("account:token:" + id);
    }

    /**
     * 描述：存储token
     * @author Cymal
     * @date 2024-06-27
     */
    public void storageToken(Long id, String point, String token) {
        // 设置token过期时间
        String timeout = configService.selectConfigByKey("account.token.timeout");
        if (StringUtils.isBlank(timeout)) {
            timeout = "8";
        }
        // 是否sso单点登录
        String sso = configService.selectConfigByKey("account.sso");
        if (Objects.equals(sso, "true")) {
            redisTemplate.opsForValue().set("account:token:" + point + ":" + id,
                    token,
                    Long.parseLong(timeout),
                    TimeUnit.HOURS);
            return;
        }
        redisTemplate.opsForValue().set("account:token:" + id,
                token,
                Long.parseLong(timeout),
                TimeUnit.HOURS);
    }

    /**
     * 描述：存储获得token
     * @author Cymal
     * @date 2024-06-29
     */
    public String storageAndGetToken(Account account, String point) {
        String token = AccountEncUtil.token(account);
        Long id = account.getId();
        storageToken(id, point, token);
        return token;
    }

}
